export default {
  data() {
    return {
      form: {},
      pageConfig: {
        current: "current",
        size: "size",
      },
      page: this.initPage(),
      query: {},
      selectionList: [],
      loading: true,
      data: [],
      keyId: "id"
    }
  },
  methods: {
    initPage() {
      return {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      }
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    // 刷新
    refreshChange() {
      this.onLoad(this.page);
    },
    // 搜索重置
    searchReset() {
      this.onLoad(this.page);
    },
    // 搜索
    searchChange(params, done) {
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    // 表格勾选
    selectionChange(list) {
      this.selectionList = list;
    },
    // 勾选清空
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    // 关闭弹框
    beforeClose(done) {
      done();
    },
    // 加载
    onLoad(page = this.page, params = {}) {
      this.loading = true;
      this.getPage(Object.assign(params, this.query, this.getPageParams(page))).then(
        ({ data }) => {
          this.data = data.records;
          this.page = this.getPageReturn(data);
          this.loading = false;
        }
      );
    },
    // 编辑
    rowUpdate(row, index, done, loading) {
      this.update(row).then(
        () => {
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          // 数据回调进行刷新
          done(row);
          this.onLoad();
        },
        () => {
          loading();
        }
      );
    },
    // 新增
    rowSave(row, done, loading) {
      this.add(row).then(
        () => {
          // 获取新增数据的相关字段
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          // 数据回调进行刷新
          done();
          this.onLoad();
        },
        () => {
          loading();
        }
      );
    },
    // 删除
    rowDel(row, index, done) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return this.remove(row[this.keyId]);
        })
        .then(() => {
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          // 数据回调进行刷新
          done();
          this.onLoad();
        });
    },
    // 返回页码
    getPageParams(page = this.page) {
      return {
        current: page.currentPage,
        size: page.pageSize,
      }
    },
    // 接受接口中的页码信息
    getPageReturn(row) {
      return {
        pageSize: row.size,
        currentPage: row.current,
        total: row.total || -1, // avue框架问题，赋值0无效
      }
    },
    beforeOpen(done) {
      done();
    },
  }
}
